package com.lcf.framework.config.satoken;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.lcf.framework.interceptor.TenantInterceptor;
import com.lcf.framework.utils.UrlUtils;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 描述：satoken
 *
 * @author lcf
 * @since 2025/2/22 15:56
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Resource
    private TokenSkipUrlConfig tokenSkipUrlConfig;
    @Resource
    private TenantInterceptor tenantInterceptor;

    /**
     * 注册 Sa-Token 拦截器，打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //不检查token的路径
        List<String> urls = tokenSkipUrlConfig.getUrls();
        // 将租户id放到线程变量中
        registry.addInterceptor(tenantInterceptor).addPathPatterns("/**");
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor(handle -> {
            if (UrlUtils.matchUrl(urls, SaHolder.getRequest().getRequestPath())) {
                return;
            }

            // 登录校验 -- 拦截所有路由
            SaRouter.match("/**", r -> StpUtil.checkLogin());

        })).addPathPatterns("/**");
    }
}

